#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;

[InitializeOnLoad]
public static class AutomaticGBKConverter
{
    static AutomaticGBKConverter()
    {
        // 这里放你原先的转码逻辑
        // 例如，只对真正的 GBK 文件做转换：
        ConvertAllGBKFilesToUTF8();
    }

    private static void ConvertAllGBKFilesToUTF8()
    {
        Debug.Log("开始自动检测并转换 GBK 文件 ...");
        
        
        string rootPath = Application.dataPath;
        string[] allFiles = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
        int convertedCount = 0;

        foreach (var filePath in allFiles)
        {
            // 过滤：仅处理特定扩展名的文本文件
            if (!IsTextFile(filePath)) 
                continue;

            // 跳过 BOM 文件
            if (HasBOM(filePath))
                continue;

            // 判断是否真正是 GBK
            if (IsDefinitelyGBKFile(filePath))
            {
                if (ConvertFileEncoding(filePath, Encoding.GetEncoding("GBK"), new UTF8Encoding(false)))
                {
                    convertedCount++;
                    Debug.Log($"[GBK->UTF8] Converted: {filePath}");
                }
            }
        }

        Debug.Log($"自动转换完成，转换了 {convertedCount} 个文件。");
    }

    // ===== 以下是与之前示例类似的辅助方法 =====
    private static bool IsTextFile(string filePath)
    {
        string ext = Path.GetExtension(filePath).ToLower();
        switch (ext)
        {
            case ".cs":
            case ".txt":
            case ".json":
            case ".shader":
            case ".xml":
            case ".csv":
            case ".lua":
            case ".py":
            case ".html":
            case ".htm":
            case ".js":
            case ".css":
                return true;
            default:
                return false;
        }
    }

    private static bool HasBOM(string filePath)
    {
        byte[] bomBytes = new byte[4];
        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            if (fs.Length < 2)
                return false;
            fs.Read(bomBytes, 0, (int)Mathf.Min(4, fs.Length));
        }

        // UTF-8 BOM: EF BB BF
        if (bomBytes[0] == 0xEF && bomBytes[1] == 0xBB && bomBytes[2] == 0xBF)
            return true;

        // UTF-16 LE BOM: FF FE
        if (bomBytes[0] == 0xFF && bomBytes[1] == 0xFE)
            return true;

        // UTF-16 BE BOM: FE FF
        if (bomBytes[0] == 0xFE && bomBytes[1] == 0xFF)
            return true;

        return false;
    }

    private static bool IsDefinitelyGBKFile(string filePath)
    {
        byte[] fileBytes = File.ReadAllBytes(filePath);

        // 跳过纯 ASCII
        if (!ContainsNonAsciiByte(fileBytes))
            return false;

        // 如果能被 UTF-8 成功解码，则认为是 UTF-8
        if (IsValidUTF8(fileBytes))
            return false;

        // 如果 UTF-8 不行，但 GBK 正常，则认为是 GBK
        if (IsValidGBK(fileBytes))
            return true;

        return false;
    }

    private static bool ContainsNonAsciiByte(byte[] bytes)
    {
        foreach (byte b in bytes)
        {
            if (b > 0x7F)
                return true;
        }
        return false;
    }

    private static bool IsValidUTF8(byte[] bytes)
    {
        try
        {
            Encoding utf8 = new UTF8Encoding(false, true);
            utf8.GetString(bytes); 
            return true;
        }
        catch
        {
            return false;
        }
    }

    private static bool IsValidGBK(byte[] bytes)
    {
        try
        {
            Encoding gbk = Encoding.GetEncoding("GBK",
                            new EncoderExceptionFallback(),
                            new DecoderExceptionFallback());
            gbk.GetString(bytes);
            return true;
        }
        catch
        {
            return false;
        }
    }

    private static bool ConvertFileEncoding(string filePath, Encoding srcEncoding, Encoding dstEncoding)
    {
        try
        {
            byte[] srcBytes = File.ReadAllBytes(filePath);
            string content = srcEncoding.GetString(srcBytes);
            byte[] dstBytes = dstEncoding.GetBytes(content);
            File.WriteAllBytes(filePath, dstBytes);
            return true;
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"转码失败: {filePath}, 错误：{ex.Message}");
            return false;
        }
    }
}
#endif